package com.txtsqlclient.ui.si;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.dataaccess.database.connection.ConnectionException;
import com.txtsqlclient.dataaccess.database.connection.ConnectionFactory;
import com.txtsqlclient.domain.FileDataSource;
import com.txtsqlclient.ui.Messages;
import com.txtsqlclient.ui.exception.SubInterfaceException;
import com.txtsqlclient.ui.helper.UserInputCapturer;
import com.txtsqlclient.ui.vo.Session;

public class FileInfoSubInterface extends PromptBasedSubInterface {

	private String dirPath;

	private final static Log LOGGER = LogFactory
			.getLog(FileInfoSubInterface.class);

	public void gatherInput(Session session) throws SubInterfaceException {
		try {
			readDirPath();
		} catch (IOException ie) {
			throw new SubInterfaceException(
					"Error while reading user input from console:", ie);
		}
	}

	protected void readDirPath() throws IOException {
		this.dirPath = UserInputCapturer
				.getLine("Please enter the path of the directory containing the file:");
		if (this.dirPath == null || this.dirPath.length() == 0) {
			System.out.println(Messages.IP_ERROR.toUpperCase());
			// Try to read IP again.
			readDirPath();
		}
	}

	public void handleInput(Session session) throws SubInterfaceException {
		List<String> errors = new ArrayList<String>();
		if (session.getDsType() == null) {
			errors.add(Messages.DSTYPE_ERROR);
		}
		if (this.dirPath == null || this.dirPath.trim().length() == 0) {
			errors.add(Messages.DIRPATH_ERROR);
		}
		if (!errors.isEmpty()) {
			throw new IllegalArgumentException(Arrays
					.toString(errors.toArray()));
		}

		FileDataSource file = new FileDataSource(session.getDsType(),
				this.dirPath);
		try {
			ConnectionFactory.getInstance().getConnection(file);
			LOGGER.debug("Obtained connection to the data source.");
			session.setDataSource(file);
		} catch (ConnectionException e) {
			throw new SubInterfaceException(
					"Problem connection to database with the given details. Please verify login information, or try again later",
					e);
		}
	}

}
